#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 20;
int arr[N];
struct node
{
	int a, b;
}S[N];
int n, H, M;
int cmp(node a, node b)
{
	if (a.a != b.a)return a.a < b.a;
	return a.b < b.b;
}
int main()
{
	int t;
	cin >> t;
	while (t--) {
		cin >> n >> H >> M;
		int ans1 = H * 60 + M;
		bool flag = 0;
		for (int i = 0; i < n; i++) {
			int h, m;
			cin >> h >> m;
			arr[i] = h * 60 + m;
			if (arr[i] == ans1)flag = 1;
		}
		if (flag)cout << "0 0" << endl;
		sort(arr, arr + n);
		int b = arr[n - 1];	
	    if (ans1 > b) {
			int ans = 24 * 60 - ans1;
			cout << (b + ans) / 60 << " " << (b + ans) % 60 << endl;
		}
		else {
			int ans2 = 0;
			for (int i = 0; i < n; i++) {
				if (arr[i] > ans1) {
					ans2 = arr[i];
					break;
				}
			}
			cout << (ans2 - ans1) / 60 << " " << (ans2 - ans1) % 60 << endl;
		}
		/*int ans2 = a * 60 + b;
		if (ans1 == ans2) {
			cout << "0 0" << endl;
		}
		else if (ans1 > ans2) {
			int ans = 24 * 60 - ans1;
			cout << (ans2 + ans) / 60 << " " << (ans2 + ans) % 60 << endl;
		}
		else {
			cout << (ans2 - ans1) / 60 << " " << (ans2 - ans1) % 60 << endl;
		}*/
	}
	return 0;
}